package com.markhsiu.map;

//http://blog.csdn.net/u014376020/article/details/50455470
public class BitMap {
    public static final byte B = 1;
    public static final byte KB = 2;
    public static final byte MB = 3;
    private static final byte[] bit = new byte[] { -128, 0x40, 0x20, 0x10, 0x8, 0x4, 0x2, 0x1 };
    private final int mMemory;
    private int mAvailableSize;
    private byte mArray[];

    private BitMap() {
        mMemory = 0;
    }
    // 指定bitmap的内存大小
    BitMap(int memory, int units) {
        switch (units) {
        case B:
            mMemory = memory;
            break;
        case KB:
            mMemory = memory * 1024;
            break;
        case MB:
            mMemory = memory * 1048576;
            break;
        default:
            throw new IllegalArgumentException("参数units必须在1~3之间");
        }
        mArray = new byte[mMemory];
        mAvailableSize = mMemory * 8;
    }
    // 添加元素
    public boolean add(int num) {
        if (num >= mMemory * 8) {
            return false;
        }
        mArray[num / 8] |= bit[num % 8];
        mAvailableSize--;
        return true;
    }
    // 检查此元素是否存在
    public boolean isInMap(int num, boolean flag) {
        if (num >= mMemory * 8) {
            return false;
        }
        return ((mArray[num / 8] & bit[num % 8]) != 0);
    }

    // 返回能存储的数据个数
    public int getMemory() {
        return mAvailableSize;
    }
}